<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page language="java" contentType="text/html; charset=utf-8"
         pageEncoding="utf-8" %>
<html>
<head>
    <base href="http://localhost:8080/">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>购物车</title>
    <link href="static/css/bootstrap.min.css" rel="stylesheet">
    <script type="text/javascript" src="static/js/jquery-1.12.4.js"></script>
    <script type="text/javascript">
        /*
         *  该方法是对购物车是否为空进行判断
         */
        var isEmpty = function () {
            if ($("tr:not(:first)").length == 0) {
                $("#emptyCart").html("");
                $("#emptyCart").append("<h3>购物车空空如也！快去购物车吧！</h3>")
            }
        };
        /*
         * 该方法是对小计进行计算使其动态生成
         */
        var sum = function () {
            var total = 0;
            $(".ccount span").each(function () {
                total += parseInt($(this).text());
            });
            $("#total b").html(total);
        };

        /**
         * 实现商品的“+“，”—“，直接修改文本框的方法。
         * 以下是“-”
         */
        var btnDelete = function () {
            $("button[name='btn-']").click(function () {
                var text = $(this).parent().next();//获取下一个兄弟结点
                cid = $(text).attr("cid");
                if (text.val() <= 1) {
                    if (confirm("确定要移除该商品吗？")) {
                        //获取当前的tr
                        var thisTr = document.getElementById("content");
                        thisTr.remove();
                        $.post("/cart?method=deleteOne", {"cid": cid}, function () {
                            //判断购物车是否为空
                            isEmpty();
                            //重新计算总金额
                            sum();
                        });
                    }
                } else {
                    var cnumobj = $(text).val(parseInt($(text).val()) - 1);
                    var cnum = cnumobj.val();

                    //计算并设置小计
                    var price = $(this).parent().parent().parent().prev().html();
                    var ccount = parseInt(cnum * price * 100) / 100.0;

                    $(this).parent().parent().parent().next().children("span").text(ccount);
                    //重新计算总金额
                    $.post("/cart?method=update", {"cid": cid, "cnum": cnum, "ccount": ccount}, sum());

                }

            });
        }
        /**
         * 以下是“＋”
         */
            //获取button中name是btn+的；
        var btnPlus = function () {
                $("button[name='btn+']").click(function () {
                    var text = $(this).parent().prev();//获取下一个兄弟结点
                    var cnumobj = $(text).val(parseInt($(text).val()) + 1);//获取当前行的数量text
                    var cnum = cnumobj.val();//获取当前行的数量text的值
                    cid = $(text).attr("cid");

                    //计算并设置小计
                    var price = $(this).parent().parent().parent().prev().html();
                    var ccount = parseInt(cnum * price * 100) / 100.0;
                    //将改变的值写入
                    $(this).parent().parent().parent().next().children("span").text(ccount);
                    //重新计算总金额
                    sum();
                    $.post("/cart?method=update", {"cid": cid, "cnum": cnum, "ccount": ccount});

                });
            }

        /**
         * 以下是直接修改text窗口修改
         */
        var text = function () {
            $(":text").change(function () {
                var reg=new RegExp(/^[1-9]\d*$/);
                var cnumobj = $(this).val(parseInt($(this).val()));
                var cnum = cnumobj.val();
                cid = $(this).attr("cid");
                var price = $(this).parent().parent().prev().html();
                if (reg.test(cnum)){
                //计算并设置小计
                var ccount = parseInt(cnum * price * 100) / 100.0;
                $(this).parent().parent().next().children("span").text(ccount);
                //重新计算总金额
                sum();
                $.post("/cart?method=update", {"cid": cid, "cnum": cnum, "ccount": ccount});
                } else {
                    alert("输入数量不合法");
                    cnumobj.val(1);
                    cnum = cnumobj.val();
                    //计算并设置小计
                     ccount = parseInt(cnum * price * 100) / 100.0;
                    $(this).parent().parent().next().children("span").text(ccount);
                    //重新计算总金额
                    sum();
                    $.post("/cart?method=update", {"cid": cid, "cnum": cnum, "ccount": ccount});
                }
            });

        }
        /**
         * 删除单件商品
         */
        var deleteOne = function () {
            $("button[name='deleteOne']").click(function () {
                if (confirm("确定要移除该商品吗？")) {
                    cid = $(this).attr("cid");
                    $.get("/cart?method=deleteOne&cid=" + cid, function () {
                        isEmpty();
                        sum();
                    });
                    this.parentNode.parentNode.remove();
                }
            });
        };
        /**
         * 以下是实现清空购物车功能
         */
        var removeAll = function () {
            $("#removeAllProduct").click(function () {
                //表示整个信息tr
                if (confirm("确定要删除全部吗？一旦删除无法恢复")) {
                    //删除所有的tr
                    $("tr").remove();
                    //通过回调使页面刷新
                    $.get("/cart?method=clear", function () {
                        //通过回调函数返回如果购物车为空，输出h3
                        isEmpty();
                        sum();
                    });
                }
            })
        }
        /**
         *  异步生成整个购物车界面
         */
        $(function () {
            sum();
            isEmpty();
            var req = new XMLHttpRequest();
            var cid = null;
            var uid =${sessionScope.uid};
            req.open("GET", "/cart?method=show&uid=" + uid, true);
            req.onreadystatechange = function () {
                if (req.readyState == 4 && req.status == 200) {
                    //删除单品
                    deleteOne();
                    //减键
                    btnDelete();
                    //加键
                    btnPlus();
                    //文本框修改
                    text();
                    //清空购物车
                    removeAll();
                }
            };
            req.send();
        })

    </script>
</head>
<body style="background-color:#f5f5f5">
<%@ include file="../common/header.jsp" %>
<div class="container" style="background-color: white;">
    <div class="row" style="margin-left: 40px">
        <h3>我的购物车
            <small>温馨提示：产品是否购买成功，以最终下单为准哦，请尽快结算</small>
        </h3>
    </div>
    <div class="row" style="margin-top: 40px;" id="emptyCart">
        <c:if test="${!empty requestScope.carts}">
            <div class="col-md-10 col-md-offset-1">

                <table class="table table-bordered table-striped table-hover">
                    <tr>
                        <th>序号</th>
                        <th>商品名称</th>
                        <th>价格</th>
                        <th>数量</th>
                        <th>小计</th>
                        <th>操作</th>
                    </tr>
                    <c:set value="0" var="sum"></c:set>
                    <c:forEach items="${requestScope.carts}" var="c" varStatus="i">
                        <tr id="content">
                            <th>${i.count}</th>
                            <th>${c.product.pname}</th>
                            <th class="pprice">${c.product.pprice}</th>
                            <th width="100px">
                                <div class="input-group">
		 						<span class="input-group-btn">
		 							<button class="btn btn-default" type="button" name="btn-">-</button>
		 						</span>
                                    <input type="text" class="form-control" id="num_count${i.count}" value="${c.cnum}"
                                           style="width:40px" cid="${c.cid}">
                                    <span class="input-group-btn">
		 							<button class="btn btn-default" type="button" name="btn+">+</button>
		 						</span>
                                </div>
                            </th>
                            <th class="ccount">¥&nbsp;<span>${c.ccount }</span></th>
                            <th>
                                <button type="button" class="btn btn-default" name="deleteOne" cid="${c.cid}">删除
                                </button>
                            </th>
                        </tr>
                        <c:set var="sum" value="${sum+c.ccount}"></c:set>
                    </c:forEach>
                </table>
            </div>
        </c:if>
    </div>
    <hr>
    <div class="row">
        <div class="pull-right" style="margin-right: 40px;">

            <div>
                <a id="removeAllProduct" href="javascript:clearCart(0)" class="btn btn-default btn-lg">清空购物车</a>
                &nbsp;&nbsp;
                <a href="order?method=preview&uid=${sessionScope.user.uid}" class="btn  btn-danger btn-lg">添加收货地址</a>

            </div>
            <br><br>
            <div style="margin-bottom: 20px;">
                商品金额总计：<span id="total" class="text-danger">￥&nbsp;&nbsp;<b>${sum}</b></span>
            </div>
        </div>
    </div>
</div>


<!-- 底部 -->
<%@ include file="/pages/common/footer.jsp" %>

</body>
</html>